package com.orion.config;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.Header;
import cn.hutool.json.JSONUtil;
import com.orion.domain.Result;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 * @date 2021/9/28
 */
public class CustomOauth2AccessDenyHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        System.out.println("AccessDeniedException in CustomOauth2AccessDenyHandler : " + accessDeniedException.toString());
        Result result = new Result(accessDeniedException.getMessage(), -1);
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setHeader(Header.CONTENT_TYPE.name(), MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
